//
//  InvestverifVC.m
//  ZZLC
//
//  Created by 杨春至 on 2017/12/14.
//  Copyright © 2017年 ZhongZeng. All rights reserved.
//

#import "InvestverifVC.h"
#import "InvestTableViewCell.h"
#import "InvestDetailHeadView.h"
#import "AgreeView.h"
#import "BottomSelectTableView.h"
#import "CoverView.h"
#import "CountModel.h"
#import "BankModel.h"
#import "InputSecretVC.h"
#import "SuccessInvestVC.h"

typedef NS_ENUM(NSInteger,BuyType) {
    Invest_BankType,
    Invest_leftMoneyType
};

@interface InvestverifVC ()<UITableViewDelegate,UITableViewDataSource,TTTAttributedLabelDelegate,UITextFieldDelegate>
{
    NSArray *_titleArray;
    NSArray *_canEditArray;
    NSMutableArray *_placeHodlerArray;
    NSMutableArray *_dataArrary;
    UITextField *_tf1;
    UITextField *_tf2;
    BOOL _agreeFlag;
    NSInteger _coupon;//优惠券金额
    BuyType _buyType;//购买方式
}
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) UIButton *investBtn;

@property (nonatomic,strong) TTTAttributedLabel *infoLb;

@property (nonatomic,strong) AgreeView *bottomAgreeView;

@property (nonatomic,strong) UIWindow *window;

@property (nonatomic,strong) CoverView *cover;

@property (nonatomic,strong) BottomSelectTableView *bottomTablew;

@property (nonatomic,strong) CountModel *countModel;//账户model

@property (nonatomic,strong) BankModel *bankModel;//银行卡信息

@property(nonatomic)InputSecretVC *inputSecretVc;

@end

@implementation InvestverifVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //    [self loadData];
    [self configUI];
}

//进行支付
- (void)startInvest{
    
    NSInteger inputNum = [_tf1.text integerValue];
    NSInteger leftNum = [_countModel.leftMoney integerValue];
    if (!_agreeFlag) {
        [QMUITips showError:@"温馨提示" detailText:@"请阅读或同意中增理财服务协议" inView:self.view hideAfterDelay:1.8];
        return;
    }else if (inputNum < 1){
        [QMUITips showError:@"温馨提示" detailText:@"请输入购买金额" inView:self.view hideAfterDelay:1.8];
        return;
    }else if (inputNum < [_model.tzqx integerValue]){
        NSString *alterStr =  [NSString stringWithFormat:@"购买金额必须大于%@",_model.tzqx];
        [QMUITips showError:@"温馨提示" detailText:alterStr inView:self.view hideAfterDelay:1.8];
        return;
    }else if (inputNum % 50 != 0){
        [QMUITips showError:@"温馨提示" detailText:@"投资金额必须为50的整数倍" inView:self.view hideAfterDelay:1.8];
        return;
    }else if (inputNum > leftNum){
        [QMUITips showError:@"温馨提示" detailText:@"项目余额不足" inView:self.view hideAfterDelay:1.8];
        return;
    }else if (inputNum <= 1){
        [QMUITips showError:@"温馨提示" detailText:@"请输入购买金额" inView:self.view hideAfterDelay:1.8];
        return;
    }else{
        if (_buyType == Invest_leftMoneyType) {
            //            余额购买
            if ([_countModel.isPayPwd isEqualToString:@"yes"]) {
                [self buyInvestByRestMoney];
            }else{
                //                设置交易密码
                [self setPaypassword];
            }
        }else{
            //            银行卡购买
            [self buyInvestBybankCard];
        }
    }
    
}
- (void)buyInvestByRestMoney{
    
    if ([_tf1.text integerValue]>[_countModel.leftMoney integerValue]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的账户余额不足,现在去充值?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *rechargeAction = [UIAlertAction actionWithTitle:@"充值" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self gotoCharge];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:rechargeAction];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else{
        __weak typeof (self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.view addSubview:self.inputSecretVc.view];
        });
    }
}

- (void)setPaypassword{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"为保证您的账户安全 您需要设置六位交易密码" preferredStyle:UIAlertControllerStyleAlert];
    [alertView addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入交易密码";
        textField.keyboardType  = UIKeyboardTypeNumberPad;
        textField.delegate = self;
        textField.secureTextEntry = YES;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alertView addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请再次输入交易密码";
        textField.keyboardType  = UIKeyboardTypeNumberPad;
        textField.delegate = self;
        textField.secureTextEntry = YES;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UITextField *pass1 = alertView.textFields.firstObject;
    UITextField *pass2 = alertView.textFields.lastObject;
    UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (pass1.text.length!=6) {
            [QMUITips showError:@"密码长度不正确" inView:self.view hideAfterDelay:1];
            [self presentViewController:alertView animated:YES completion:nil];
            return ;
        }else
            if (![pass1.text isEqualToString:pass2.text]) {
                [QMUITips showError:@"密码长度不正确" inView:self.view hideAfterDelay:1];
                [self presentViewController:alertView animated:YES completion:nil];
                return;
            }else{
                
                NSMutableDictionary *params = @{
                                                @"username":[UserModel userName],
                                                @"password":pass2.text,
                                                @"pwd":pass1.text,
                                                @"authorization":[UserModel authorization],
                                                }.mutableCopy;
                [NetWorkingManager postWithRequestUrl:@"User/updatePayPwd" AndParameters:@{@"parameters":[params DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
                    [QMUITips showSucceed:@"设置交易密码成功" inView:self.view hideAfterDelay:1];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        _countModel.isPayPwd = @"yes";
                        [self buyInvestByRestMoney];
                    });
                } FailBlock:^(NSDictionary *errDic) {
                    [QMUITips showError:@"温馨提示" detailText:errDic[@"errorMsg"] inView:self.view hideAfterDelay:1.8];
                }];
            }
        
        
    }];
    [alertView addAction:doneAction];
    [alertView addAction:setAction];
    [self presentViewController:alertView animated:YES completion:nil];
}
#pragma mark ########购买理财产品########
- (void)buyInvestBypassWord:(NSString *)password{
    

    NSMutableDictionary *params = @{@"productId":_model.ID,
                                    @"platform":@"2",
                                    @"username":[UserModel userName],
                                    @"acc_no":_bankModel?_bankModel.bankAccount:@"",
                                    @"type":@"2",
                                    @"copies":_tf1.text,
                                    @"coupon":[NSString stringWithFormat:@"%ld",_coupon*100],
                                    @"couponId":@"",
                                    @"id_card":@"",
                                    @"id_holder":[UserModel userName],
                                    @"inMoney":[NSString stringWithFormat:@"%@00",_tf1.text],
                                    @"bankMoney":@"0",
                                    @"authorization":[UserModel authorization],
                                    @"payPassword":password,
                                    @"uuid":[ZZHelper createCUID],
                                    }.mutableCopy;
    NSString *url = @"";
    //    普通理财
    if ([_model.productType isEqualToString:@"0"]) {
        url = @"User/buyProject";
    }else{
        //    新手理财
        url = @"User/buyFreshProject";
        [params setObject:@"18516773736" forKey:@"investorsId"];
    }
    
    
//    investorsId
    [NetWorkingManager postWithRequestUrl:url AndParameters:@{@"parameters":[params DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
        [QMUITips showSucceed:@"购买成功" inView:self.view hideAfterDelay:2];

        if ([url isEqualToString:@"User/buyFreshProject"]) {
            
            NSMutableDictionary *dict = [UserModel userDic].mutableCopy;
            [dict setObject:@"1" forKey:@"buyFreshmanProduct"];
            [[NSUserDefaults standardUserDefaults]setObject:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]forKey:K_USER_MODEL];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
//     购买成功页面
        SuccessInvestVC *successVC  = [[SuccessInvestVC alloc]init];
        [self.navigationController pushViewController:successVC animated:YES];
//
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.navigationController popToRootViewControllerAnimated:YES];
//        });
    } FailBlock:^(NSDictionary *errDic) {
        [QMUITips showError:@"温馨提示" detailText:errDic[@"errorMsg"] inView:self.view hideAfterDelay:1.8];
    }ShowTips:NO];
    
    
}
//去充值
- (void)gotoCharge{
    
}
- (void)buyInvestBybankCard{
    NSMutableDictionary *params = @{@"productId":_model.ID,
                                    @"platform":@"2",
                                    @"username":[UserModel userName],
                                    @"acc_no":_bankModel.bankAccount,
                                    @"type":@"2",
                                    @"copies":_tf1.text,
                                    @"coupon":[NSString stringWithFormat:@"%ld",_coupon*100],
                                    @"couponId":@"",
                                    @"id_card":@"",
                                    @"id_holder":@"",
                                    @"inMoney":@"0",
                                    @"pay_code":_bankModel.bankCode,
                                    @"authorization":[UserModel authorization]
                                    }.mutableCopy;
    [NetWorkingManager postWithRequestUrl:@"User/rechargeAndBuy" AndParameters:@{@"parameters":[params DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
        
    } FailBlock:^(NSDictionary *errDic) {
        [QMUITips showError:@"温馨提示" detailText:errDic[@"errorMsg"] inView:self.view hideAfterDelay:1.8];
    }ShowTips:NO];
}
- (void)loadData{
    NSString *placeHoldertxt = [NSString stringWithFormat:@"%ld起投,且为50的整数倍",[_model.atleastMoney integerValue]/100];
    _agreeFlag = YES;
    _buyType = Invest_leftMoneyType;
    _titleArray = @[@[],@[@"投资金额",@"到期收益"],@[@"支付方式"]];
    _canEditArray = @[@[],@[@1,@0],@[@0]];
    _dataArrary = @[@[],@[@"",@""],@[@""]].mutableCopy;
    _placeHodlerArray = @[@[],@[placeHoldertxt,@""],@[@"可用余额 10000"]].mutableCopy;
    
    NSDictionary *param = @{@"authorization":[UserModel authorization]};
    [NetWorkingManager postWithRequestUrl:@"User/showMyAccount" AndParameters:@{@"parameters":[param DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
        NSLog(@"%@",responseObject);
        self.countModel  = [CountModel objectWithKeyValues:[responseObject objectForKey:@"obj"]];
        NSString *alStr = [NSString stringWithFormat:@"剩余%@可用余额",[NSString stringWithFormat:@"可用余额:%.2f",[_countModel.leftMoney floatValue]/100]];
        _placeHodlerArray[2] = @[alStr];
        if ([responseObject.allKeys containsObject:@"list"]) {
            NSArray *bankArray = [BankModel objectArrayWithKeyValuesArray:responseObject[@"list"]];
            if (bankArray.count>=1) {
                self.bankModel = [bankArray firstObject];
            }
        }
        [self.tableView reloadData];
    } FailBlock:^(NSDictionary *errDic) {
        
    }];
    
}
- (void)configUI{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.investBtn];
}
- (void)showCover{
    if (!_cover) {
        [self.window addSubview:self.cover];
        [self.window addSubview:self.bottomTablew];
    }
    _cover.alpha = 0.4;
    [UIView animateWithDuration:0.4 animations:^{
        _bottomTablew.bottom = KHeight;
    }];
}
- (void)hideCover{
    _cover.alpha = 0;
    [UIView animateWithDuration:0.4 animations:^{
        _bottomTablew.bottom = KHeight+ 160;
    }];
    
}
#pragma mark ######更新text
- (void)updateDataBytext:(NSString *)text{
    float x = [text floatValue]/365/100;
    NSInteger days = [_model.lcqx integerValue];
    NSInteger interestV = [_model.baseEarnings floatValue]+[_model.jiangLiEarnings floatValue];
    //    [_model.lcqx integerValue];
    NSString *ansStr = [NSString stringWithFormat:@"%.2f",x*interestV*days];
    _tf2.text = ansStr;
    _dataArrary[1] = @[text,_tf2.text];
}
- (void)viewDidLayoutSubviews{
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 44, 0));
    }];
    [_investBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(_tableView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    if (label==_infoLb) {
        [self jumpToH5VCByURL:[NSString stringWithFormat:@"%@%@",HOSTURL_FOR_REPORT,@"assetzz/mobileH5/prompt.jsp"]];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && indexPath.row==0) {
        if (!_bankModel||!_countModel) {
            [QMUITips showError:@"温馨提示" detailText:@"银行卡信息缺失"  inView:self.view hideAfterDelay:1.2];
        }else{
            [self showCover];
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        InvestDetailHeadView *headView =  [[[NSBundle mainBundle]loadNibNamed:@"InvestDetailHeadView" owner:nil options:NULL]firstObject];
        if (_model) {
            headView.model = self.model;
        }
        return headView;
    }else{
        return self.infoLb;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 2) {
        UIView *footerView = [[UIView alloc]init];
        [footerView addSubview:self.bottomAgreeView];
        [_bottomAgreeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(footerView);
            make.height.equalTo(@30);
            make.width.equalTo(@200);
        }];
        return footerView;
    }else{
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 150;
    }else if (section == 1) {
        return 10.00;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 2) {
        return 40;
    }else{
        return 0.001f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    InvestTableViewCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"InvestTableViewCell" owner:nil options:NULL]firstObject];
    [cell setTitleStr:_titleArray[indexPath.section][indexPath.row] canEditStr:[_canEditArray[indexPath.section][indexPath.row] boolValue] editText:_dataArrary[indexPath.section][indexPath.row] placeHodel:_placeHodlerArray[indexPath.section][indexPath.row]];
    if (indexPath.section!=1) {
        [cell hideRightUnitLb];
    }
    if (indexPath.section == 2&&indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }else if (indexPath.section == 1&&indexPath.row == 0){
        cell.desLb.keyboardType = UIKeyboardTypeNumberPad;
        _tf1 = cell.desLb;
        cell.block = ^(NSString *text) {
            [self updateDataBytext:text];
        };
    }else if (indexPath.section == 1&&indexPath.row == 1){
        _tf2 = cell.desLb;
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else if (section == 1) {
        return 2;
    }else{
        return 1;
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *lastStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //    textField.text = lastStr;
    if (lastStr.length>6) {
        return NO;
    }
    return YES;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (TTTAttributedLabel *)infoLb{
    if (!_infoLb) {
        _infoLb = [TTTAttributedLabel new];
        _infoLb.frame = CGRectMake(0, 0, KWidth, 35);
        [_infoLb setStlyeByText:@"       银行卡支付 (充值错误码含义)" andLinkText:@"(充值错误码含义)"];
        _infoLb.delegate = self;
    }
    return _infoLb;
}

- (AgreeView *)bottomAgreeView{
    if (!_bottomAgreeView) {
        _bottomAgreeView = [[AgreeView alloc]initwithText:@"我已阅读《中增理财服务协议》" andLinkText:@"《中增理财服务协议》" Selectblock:^{
            //            http://192.168.2.66:8080/huoqWap/Product/huoq/protocol_service.jsp
            [self jumpToH5VCByURL:[NSString stringWithFormat:@"%@%@",HOSTURL_FOR_REPORT,@"assetzz/protocol_service.jsp"]];
            NSLog(@"%@",[NSString stringWithFormat:@"%@assetzz/service.jsp",HOSTURL_FOR_REPORT]);

        } StateChangeBlock:^(BOOL nowState) {
            _agreeFlag = nowState;
        }];
    }
    return _bottomAgreeView;
}
- (UIButton *)investBtn{
    if (!_investBtn) {
        _investBtn = [[UIButton alloc]init];
        [_investBtn setBackgroundImage:UIImageMake(@"bottombtnbgcolor") forState:UIControlStateNormal];
        [_investBtn setTitle:@"立 即 支 付" forState:UIControlStateNormal];
        [_investBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _investBtn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [_investBtn bk_addEventHandler:^(id sender) {
            [self  startInvest];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _investBtn;
}
- (UIWindow *)window{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    return window;
}
- (BottomSelectTableView *)bottomTablew{
    if (!_bottomTablew) {
        if (!_bankModel||!_countModel) {
            //            [QMUITips showError:@"温馨提示" detailText:@"银行卡或者账户信息缺失"  inView:self.view hideAfterDelay:1.2];
        }else{
            NSArray *bDataSource = @[@{@"icon":_bankModel.bankCode,@"titleStr":[NSString stringWithFormat:@"%@(尾号%@)", _bankModel.bankName,_bankModel.cardLast],@"detilStr":_bankModel.bankNote,@"ischoosed":@0},@{@"icon":@"restmoneyIcon",@"titleStr":@"账户余额",@"detilStr":[NSString stringWithFormat:@"可用余额:%.2f",[_countModel.leftMoney floatValue]/100],@"ischoosed":@0}];
            NSArray *bdata = [boModel objectArrayWithKeyValuesArray:bDataSource];
            _bottomTablew = [[BottomSelectTableView alloc]initWithFrame:CGRectMake(0, KHeight+200, KWidth, 160) anDataArray:[bdata mutableCopy] ClickBlock:^(NSInteger index) {
                boModel *mModel = bdata[index];
                if (index == 0) {
                    _dataArrary[2] = @[mModel.titleStr];
                    _buyType = Invest_BankType;
                    [_tableView reloadData];
                }else{
                    _dataArrary[2] = @[mModel.detilStr];
                    _buyType = Invest_leftMoneyType;
                    [_tableView reloadData];
                }
                
                [self hideCover];
            }];
            
        }
    }
    return _bottomTablew;
}
- (CoverView *)cover{
    if (!_cover) {
        _cover = [[CoverView alloc]initWithHidenBlock:^{
            [self hideCover];
        }];
    }
    return _cover;
}
-(InputSecretVC *)inputSecretVc{
    //    if (_inputSecretVc) {
    //        return _inputSecretVc;
    //    }
    _inputSecretVc = [[InputSecretVC alloc] init];
    _inputSecretVc.view.frame = (CGRect){0,0,K_SCREEN_WIDTH,K_SCREEN_HEIGHT};
    __weak typeof (self) weakSelf = self;
    _inputSecretVc.block = ^(NSString *secret){
        [weakSelf buyInvestBypassWord:secret];
    };
    return _inputSecretVc;
}
@end

